<template>
	<view :class="[formItem.config.class, 'flex-normal']">
		<template v-if="formItem.config.model == 'appModel3'">
			<template v-if="!vuex_activity.showStatus">
				<view class="btn-item poster-btn flex-center"
					:style="{
						'font-family': setAttr('posterBtn', 'fontFamily'),
						'font-size': pxToRpx(setAttr('posterBtn', 'fontSize')),
						'color': setAttr('posterBtn', 'color'),
					}" @click="savePoster">
					{{ setAttr('posterBtn', 'text')}}
				</view>
			</template>
      <view :class="['btn-item buy-btn flex-center', vuex_activity.showStatus && 'bs']"
        :style="{
          'font-family': setAttr('buyBtn', 'fontFamily'),
          'font-size': pxToRpx(setAttr('buyBtn', 'fontSize')),
          'color': setAttr('buyBtn', 'color'),
        }" @click="toBuy">
        {{ vuex_activity.showStatus ? '立即兑换' : setAttr('buyBtn', 'text') }}
      </view>
		</template>
    <template v-if="formItem.config['model'] == 'appModel5'">
			<template v-if="!vuex_activity.showStatus">
				<view class="btn-item poster-btn flex-center"
				  :style="{
				    'font-family': setAttr('posterBtn', 'fontFamily'),
				    'font-size': pxToRpx(setAttr('posterBtn', 'fontSize')),
				    'color': setAttr('posterBtn', 'color'),
				  }" @click="savePoster">
				  {{ setAttr('posterBtn', 'text')}}
				</view>
			</template>
      <view :class="['btn-item buy-btn flex-center', vuex_activity.showStatus && 'bs']"
        :style="{
          'font-family': setAttr('buyBtn', 'fontFamily'),
          'font-size': pxToRpx(setAttr('buyBtn', 'fontSize')),
          'color': setAttr('buyBtn', 'color'),
        }" @click="toBuy">
        {{ vuex_activity.showStatus ? '立即兑换' : setAttr('buyBtn', 'text') }}
      </view>
    </template>
		
		<uni-popup zIndex="100" ref="pickerView" type="bottom" style="z-index: 9999999;">
			<view class="popup-view submit-popup">
				<view class="popup-header">
					<view class="header-title flex-normal">
						<image class="header-logo" src="/static/image/a-logo.png"></image>
						<text class="header-txt">爱车多多</text>						
					</view>
					<view class="header-desc flex-normal">
						购买后请关注 <text class="desc-txt">爱车多多</text> 公众号核销使用
					</view>
				</view>
				<view class="order-popup">
					<template v-if="!priceProp.giveStatus">
						<view class="row-item flex-between">
							<view class="item-label ellipsis-1">
								{{vuex_activity.activityName}}
							</view>
							<view class="num-content flex-normal">
								<text class="num-label">优惠价</text>
								<text class="num-val">{{priceProp.price}}</text>
							</view>
						</view>
					</template>
					<view class="row-item flex-between">
						<view class="item-label">
							订购数量
						</view>
						<view class="item-val">
							<u-number-box integer :min="1" :max="vuex_activity.limitation ? vuex_activity.emptionRestrict : 10000000000000"
							button-size="60" color="#ffffff"  bgColor="#0003AA" iconStyle="color: #fff"
							v-model="params.num" @change="numberBoxChange"></u-number-box>
						</view>
					</view>
					<view class="row-item flex-between">
						<view class="item-label">
							总计价格
						</view>
						<view class="num-content flex-normal">
							<text class="num-val">{{priceProp.sumPrice}}</text>
						</view>
					</view>
					<view class="row-item flex-between">
						<view class="item-label">
							车牌号
						</view>
						<view class="item-val" @click="showKeyboardQ">
							<u--input
								placeholder="请输入车牌号" fontSize="28rpx" color="#3D3D3D"
								border="none" inputAlign="right" readonly
								v-model="params.clientPlateNumber" style="pointer-events:none"
							></u--input>
							<u-keyboard ref="uKeyboard" autoChange 
							mode="car" :show="boo.showKeyboard"
							:closeOnClickOverlay="true" :overlay="true"
							@confirm="confirmKeyboard"
							@change="changeKeyboard"
							@backspace="backspace">
								<!-- <template #default> -->
									<view>{{other.keyboardVal}}</view>
								<!-- </template> -->
							</u-keyboard>
						</view>
					</view>
					<template v-if="!priceProp.giveStatus">
						<view class="row-item flex-between">
							<view class="item-label">
								车型
							</view>
							<view class="item-val">
								<u--input
									placeholder="请输入车型" fontSize="28rpx" color="#3D3D3D"
									border="none" inputAlign="right"
									v-model="params.vehicleModel"
								></u--input>
							</view>
						</view>
					</template>
					<view class="row-item flex-between">
						<view class="item-label">
							姓名
						</view>
						<view class="item-val">
							<u--input
								placeholder="请输入姓名" fontSize="28rpx" color="#3D3D3D"
								border="none" inputAlign="right"
								v-model="params.clientUserName"
							></u--input>
						</view>
					</view>
					<view class="row-item flex-between">
						<view class="item-label">
							手机号
						</view>
						<view class="item-val">
							<u--input
								placeholder="请输入手机号" fontSize="28rpx" color="#3D3D3D"
								border="none" type="number" maxlength="11"
								v-model="params.clientPhone" inputAlign="right"
							></u--input>
						</view>
					</view>
					<template v-if="!priceProp.giveStatus">
						<view class="row-item flex-between" v-if="priceProp.serveMoney && priceProp.serveMoney != '0'">
							<view class="item-label ellipsis-1">
								该订单包含技术服务费
							</view>
							<view class="num-content flex-normal">
								<text class="num-val">{{priceProp.serveMoney}} 元</text>
							</view>
						</view>
					</template>
				</view>
				<rh-submit-btn :text="vuex_activity.showStatus ? '立即兑换' : '立即购买'" position="relative" :submit-action="submit"></rh-submit-btn>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {pxToRpx} from './tools.js'
	import {getWxCode, getUrlCode, isWechat, replaceWxUrl} from '@/script/wx-premission.js'
	import {getWxUserInfo} from '@/api/common/index.js'
	import wechat from '@/script/wechat.js'
	import { isVehicleNumber } from '@/script/tools.js'
	import { mapGetters } from 'vuex'
	import {makeCover, payPrice, saveOrder} from '@/api/hd/index.js'
	export default {
		props: {
			formItem:{
				type: Object,
				default: {}
			}
		},
		computed: {
		  ...mapGetters(['vuex_activity', 'vuex_needRegister', 'vuex_location']),
		},
		data(){
			return {
				routeParams: {},
				boo: {
					showKeyboard: false
				},
				visible: false,
				priceProp: {
					giveStatus: true, // 默认保司发布
				},
				other: {
					keyboardVal: ''
				},
				params: {
					num: 1,
				},
				motes: [
					'1、购买后需在指定门店消费',
					'2、订单在购买后，一年内有效，请及时使用',
					'3、该优惠无其他捆绑消费，如订单使用有问题，请联系客服'
				]
			}
		},
		async mounted(){
			this.routeParams = uni.getStorageSync('icar-wxActive')
		},
		methods: {
			pxToRpx: pxToRpx,
			showKeyboardQ(){
				this.boo.showKeyboard = true
			},
			confirmKeyboard(val){
				let _self = this, vm = this.$refs['uKeyboard']
				_self.$set(_self.params, 'clientPlateNumber', _self.other.keyboardVal ?? '')
				_self.boo.showKeyboard = false
			},
			changeKeyboard(val){
				let _self = this
				_self.other.keyboardVal += val
			},
			backspace(){
				let _self = this
				let len = _self.other.keyboardVal.length
				if(len) {
					_self.other.keyboardVal = _self.other.keyboardVal.substr(0, len - 1);
				}
			},
			setAttr(configKey, valKey){
				let _self = this
				if(configKey == 'formItem'){
					return _self.formItem['configH5'][valKey]
				}else{
					if(!_self.formItem[configKey]) return
					return _self.formItem[configKey]['configH5'][valKey]
				}
			},
			savePoster(){
				let _self = this
				if(!_self.routeParams['a']) return
				if(_self.vuex_needRegister) {
					let {name} = _self.$$router.getRoute(_self)
					_self.$$router.replace({name: 'registerTel', query:{
						redirect: name
					}})
				}else{
					_self.$emit('get-share')
				}
			},
			async getTotalPrice(){
				let _self = this, isSuccess = false
				let params = {
					acddActivityId: _self.vuex_activity.id,
					number: _self.params.num
				}
				await payPrice(params).then(res => {
					isSuccess = true
					_self.priceProp = res.data
				})
				return isSuccess
			},
			numberBoxChange(e){
				this.params.num = e.value
				this.getTotalPrice()
			},
			async toBuy(){
				let _self = this
				if(_self.vuex_needRegister) {
					let {name} = _self.$$router.getRoute(_self)
					_self.$$router.replace({name: 'registerTel', query:{
						redirect: name
					}})
				}else{
					let isSuccess = _self.getTotalPrice()
					if(isSuccess){
						_self.$refs.pickerView.open()
					}	
				}
				
			},
			async submit(val){
				let _self = this
				return new Promise((resolve, reject) => {
					let {num, clientPlateNumber, clientUserName, clientPhone, vehicleModel = ''} = _self.params
					if(!num) {
						_self.$attention.noIcon('请设置购买数量')
						return resolve(true)
					}
					if(!isVehicleNumber(clientPlateNumber ?? '')) {
						_self.$attention.noIcon('请填写正确车牌号')
						return resolve(true)
					}
					if(!_self.priceProp.giveStatus){
						if(!vehicleModel) {
							_self.$attention.noIcon('请填写车型')
							return resolve(true)
						}
					}
					if(!clientUserName) {
						_self.$attention.noIcon('请填写姓名')
						return resolve(true)
					}
					let mPattern = /^(?:0|86|\+86)?1[3456789]\d{9}$/
					if(!mPattern.test(clientPhone)) {
						_self.$attention.noIcon('手机号格式不正确')
						return resolve(true)
					}
					let params = {
						"activityId": _self.vuex_activity.id, //活动id
						"orderCount": num, //购买数量
						clientUserName, //客户姓名
						clientPhone, //客户电话
						clientPlateNumber,//客户车牌
						vehicleModel, // 客户车型
						sharerUserId: _self.$route.query['i'] || '',
						address: _self.vuex_location['address'] || '.'
					}
					if (wechat?.isWechat()){
						params.method = 'WECHAT_JSAPI'
					}else{
						params.method = 'WECHAT_H5'
					}
					saveOrder(params).then(res => {
						let {payload, wxPayStatus, ret_msg} = res.data
						if(wxPayStatus){
							wechat.callWxPay(JSON.parse(payload), () => {
								_self.$$router.push({name: 'hdPaySuccess', query: {
									a: _self.vuex_activity['id'] || ''
								}})
							}, (msg) => {
								_self.$attention.noIcon(msg)
							})	
						}else{
							_self.$attention.noIcon('购买成功，关注公众号，查看详情')
						}
					}).finally(() => {
						_self.$refs.pickerView.close()
						resolve(true)
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	// px 转为 rpx 的函数
	@function rem($px) {
	  @return $px * 1rpx;
	}
	@mixin fontStyle($color, $size, $weight: 500) {
		color: $color;
		font-size: $size;
		font-weight: $weight;
	}
	.submit-popup{
		background-color: #fff;
		padding: 0 36rpx;
		border-radius: 16rpx 16rpx 0 0;
		.order-popup{
			padding-top: 40rpx;
			padding-bottom: 140rpx;
			.row-item{
				margin-bottom: 30rpx;
				&:last-child{
					margin-bottom: 0;
				}
			}
			.item-label{
				max-width: 400rpx;
				@include fontStyle(#3D3D3D, 28rpx);
			}
			.num-content{
				.num-label{
					margin-right: 18rpx;
					@include fontStyle(#3D3D3D, 24rpx);
				}
				.num-val{
					@include fontStyle(#3D3D3D, 28rpx);
				}
			}
		}
		.popup-header{
			padding: 20rpx 0;
			.header-logo{
				width: 48rpx;
				height: 48rpx;
			}
			.header-txt{
				margin-left: 20rpx;
				@include fontStyle(#3D3D3D, 28rpx);
			}
			.header-desc{
				margin-top: 20rpx;
				@include fontStyle(#999, 24rpx);
				.desc-txt{
					padding: 0 10rpx;
					@include fontStyle(#0003AA, 24rpx);
				}
			}
		}
	}
	.app-model-3.submit-model{
		position: relative;
		padding-top: 50rpx;
		.btn-item{
			height: 78rpx;
			flex: 1;
			&.poster-btn{
				background-color: #2D2C2A;
				border-radius: 39rpx 0 0 39rpx;
			}
			&.buy-btn{
				background: linear-gradient(to right, #D1A971, #F2DFB6);
				border-radius: 0 39rpx 39rpx 0;
			}
      &.bs{
        border-radius: 39rpx !important;
      }
		}
	}
  .app-model-5.submit-model{
    position: relative;
    padding-top: rem(50);
    .btn-item{
      height: rem(78);
      flex: 1;
      &.poster-btn{
        background: linear-gradient(to bottom, #FDF7E8, #E2C67F);
        border-radius: rem(39) 0 0 rem(39);
      }
      &.buy-btn{
        background: linear-gradient(to bottom, #47A5E3, #1964B3);
        border-radius: 0 rem(39) rem(39) 0;
      }
      &.bs{
        border-radius: 39rpx !important;
      }
    }
  }
</style>